<template>
  <uni-card title="配置项">
    <uni-row>
      <uni-col :span="6">
        <text class="inline-block mt-2" style="height: 2.5rem">
          配置名称：</text
        >
      </uni-col>
      <uni-col :span="12">
        <uni-easyinput
          v-model="configName"
          class=""
          placeholder="请输入配置名称"
          type="text"
        />
      </uni-col>
      <uni-col :span="6" :push="1">
        <button @tap="addConfig" class="h-9 bg-blue-500 text-white text-center">
          添加
        </button>
      </uni-col>
    </uni-row>
    <uni-table border stripe emptyText="暂无更多数据">
      <!-- 表头行 -->
      <uni-tr>
        <uni-th align="center" width="60">配置名</uni-th>
        <uni-th width="10" align="center">操作</uni-th>
      </uni-tr>
      <!-- 表格数据行 -->
      <uni-tr v-for="(item, index) in tabelData" :key="index">
        <uni-td>{{ item.configName }}</uni-td>
        <uni-td>
          <view>
            <button size="mini" type="primary" @tap="editConfig(item)">
              修改
            </button>
            <button
              class="ml-3"
              size="mini"
              @tap="deleteConfig(item)"
              type="warn"
            >
              删除
            </button>
          </view>
        </uni-td>
      </uni-tr>
    </uni-table>
  </uni-card>
</template>

<script lang="ts" setup>
import { useConfigStore } from '@/stores';
import { ref, defineEmits, onMounted } from 'vue';
const props = defineProps(['formData', 'name']);
const configName = ref('');
const tabelData = ref([]) as any;
const emit = defineEmits(['clearFormData', 'updateFormData']);
const addConfig = () => {
  if (configName.value) {
    saveConfig();
    uni.showToast({
      title: '添加成功',
      icon: 'none',
    });
    // 清空表单数据
    emit('clearFormData');
    configName.value = '';
    showConfig();
  } else {
    uni.showToast({
      title: '请输入配置名称',
      icon: 'none',
    });
  }
};
// 保存配置
const saveConfig = () => {
  useConfigStore().pushConfig({
    name: props.name,
    configName: configName.value,
    value: props.formData,
  });
};

onMounted(() => {
  showConfig();
});
// 遍历出需要展示的配置项函数
const showConfig = () => {
  tabelData.value = useConfigStore().getConfigByName(props.name) as any;
};
// 删除配置项函数
const deleteConfig = (item: any) => {
  useConfigStore().removeConfigByNameAndConfigName(props.name, item.configName);
  showConfig();
};
// 修改配置项函数
const editConfig = (item: any) => {
  // 传递表单数据
  emit('updateFormData', item.value);
  // 传递配置名称
  configName.value = item.configName;
  // 删除原配置项
  deleteConfig(item);
};
</script>

<style lang="scss" scoped></style>
